﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CommonLibrary.Common;
using System.IO;

namespace OAclient.Common
{
    public class FileHelper
    {
        #region tree_node_helper

        /// <summary>
        /// 获取给定目录文件下的所有文件返回ztreeNode
        /// </summary>
        /// <param name="file_path">"c:\program"</param>
        /// <returns></returns>
        public static Node GetFileTree(string file_path, string rootNode_name, string relfiletag)
        {
            Node tree = new Node(rootNode_name, "0", false, false, false, "根");
            GetFile(file_path, tree, relfiletag);
            return tree;
        }

        //wd,gx
        static int autokey;
        public static Dictionary<string, string> GetFileList(string file_path)
        {
            autokey = 0;
            Dictionary<string, string> list = new Dictionary<string, string>();
            GetFile(file_path, list);
            return list;
        }

        #region 方法

        static void GetFile(string filepath, Node node, string relfiletag)
        {
            DirectoryInfo di = new DirectoryInfo(filepath);
            node.Tag = di.FullName;
            if (!di.Exists) return;
            foreach (FileInfo file in di.GetFiles("*"))
            {
                node.Nodes.Add(new Node()
                {
                    Text = file.Name,
                    Value = "0",
                    Tag = GetRelName(file.FullName, relfiletag),
                    Expand = false,
                    ShowCheckBox = false,
                });
            }
            foreach (DirectoryInfo dir in di.GetDirectories("*"))
            {
                Node childNode = new Node()
                 {
                     Text = dir.Name,
                     Value = "0",
                     Tag = GetRelName(dir.FullName, relfiletag),
                     Expand = false,
                     ShowCheckBox = false,
                 };
                node.Nodes.Add(childNode);
                GetFile(dir.FullName, childNode, relfiletag);
            }
        }

        public struct RelFileTag
        {
            public static string sharefiletag = "Share\\";
            public static string personfiletag = "Person\\";
            public static string formfiletag = "Form\\";
            public static string platefiletag = "Plate\\";
            public static string wfappendfiletag = "WFAppend\\";
        }
        public static string GetRelName(string FullName, string reltag)
        {
            if (string.IsNullOrEmpty(FullName)) return string.Empty;
            string relname = FullName.Substring(FullName.LastIndexOf(reltag) + reltag.Length);
            return relname;
        }


        /// <summary>
        /// 用户iso用户文件列表获取
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="list"></param>
        static void GetFile(string filepath, Dictionary<string, string> list)
        {
            DirectoryInfo di = new DirectoryInfo(filepath);
            //node.Tag = di.FullName;
            if (!di.Exists) return;
            foreach (FileInfo file in di.GetFiles("*"))
            {
                list.Add(autokey.ToString(), file.FullName);
                autokey++;
            }
            foreach (DirectoryInfo dir in di.GetDirectories("*"))
            {
                //list.Add(dir.Name, dir.FullName);
                GetFile(dir.FullName, list);
            }
        }
        #endregion

        #endregion

        #region fileupload
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="_Request">HttpRequest 对象</param>
        /// <param name="_Response">HttpResponse 对象</param>
        /// <param name="_fileName">显示到客户端下载界面中的名字，必须带文件的后缀</param>
        /// <param name="_fullPath">目标文件的物理路径</param>
        /// <param name="_speed">下载速率</param>
        /// <returns>相应结果, true 表示成功</returns>
        public static bool ResponseFile(HttpRequestBase _Request, HttpResponseBase _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    double pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            //Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch (Exception e)
                {
                    return false;
                }
                finally
                {
                    br.Close();

                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }


        #endregion

        #region 公共方法

        /// <summary>
        /// 根据文件后缀返回对应MIME类型
        /// </summary>
        /// <param name="ext">文件后缀 例: .rar </param>
        /// <returns></returns>
        public static string GetFileMIME(string ext)
        {
            string mime = string.Empty;
            switch (ext.ToLower())
            {

                case ".rar":
                    mime = "application/octet-stream";
                    break;
                case ".zip":
                    mime = "application/x-zip-compressed";
                    break;
                case ".doc":
                    mime = "application/msword";
                    break;
                case ".xls":
                    mime = "application/msexcel";
                    break;
                case ".bmp":
                    mime = "image/bmp ";
                    break;
                case ".png":
                    mime = "image/png";
                    break;
                case ".jpeg":
                    mime = "image/jpeg";
                    break;
                case ".gif":
                    mime = "image/gif";
                    break;
                case ".txt":
                    mime = "text/plain";
                    break;
                case ".jpg":
                    mime = "image/jpg";
                    break;
                case ".pdf":
                    mime = "application/pdf";
                    break;
            }
            return mime;
        }


        #endregion
    }
}
